package sivin.uikit.framework

import android.os.Build
import android.view.WindowInsetsController
import android.view.WindowManager
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat


class SingleAssignment<T> {
    private var _value: T? = null
    private var isAssigned = false
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): T {
        return _value ?: throw IllegalStateException("${property.name} has not been assigned yet.")
    }

    operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, value: T) {
        if (!isAssigned) {
            _value = value
            isAssigned = true
        }
    }
}

object SystemUI {
    var mStatusBarHeight by SingleAssignment<Int>()
    var mNavigationBarHeight by SingleAssignment<Int>()
}

@Suppress("UNUSED")
fun AppCompatActivity.setNavigationBarStyle(isLight: Boolean) {
    val controller = window.insetsController
    val value = if (isLight) {
        WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
    } else {
        0
    }
    controller?.setSystemBarsAppearance(
        value,
        WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
    )
}

@Suppress("UNUSED")
fun AppCompatActivity.setFullScreen(fullScreen: Boolean) {
    if (fullScreen) {
        //低版本如果不生效可以打开下面的注释
//        window.setFlags(
//            WindowManager.LayoutParams.FLAG_FULLSCREEN,
//            WindowManager.LayoutParams.FLAG_FULLSCREEN
//        )

        window.attributes = window.attributes.apply {
            layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }

        WindowCompat.setDecorFitsSystemWindows(window, false)
        val windowInsetsControllerCompat = WindowInsetsControllerCompat(
            window, window.decorView
        )
        windowInsetsControllerCompat.hide(WindowInsetsCompat.Type.systemBars())
        windowInsetsControllerCompat.systemBarsBehavior =
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    } else {
        //低版本如果不生效可以打开这个
//        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.attributes = window.attributes.apply {
            layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
        }
        WindowCompat.setDecorFitsSystemWindows(window, true)
        val windowInsetsControllerCompat = WindowInsetsControllerCompat(
            window, window.decorView
        )
        windowInsetsControllerCompat.show(WindowInsetsCompat.Type.systemBars())
        enableEdgeToEdge()
    }
}
